<template>
  <div class="create_order">
    <Header title="生成订单"/>
    <van-contact-card type="edit" :tel="tel" :name="name" @click="onEdit" />
    <div class="content">
      <div v-for="(i,index) in store.state.orderList" :key="index">
        <van-card
          :num="i.num"
          :price="i.price"
          :title="i.title"
          :thumb="i.pic"
        />
      </div>
    </div>
    <div class="pay-wrap">
      <div >
        <span>商品金额</span>
        <span>￥{{allPrice}}</span>
      </div>
      <van-button type="warning" @click="handleCreateOrder" color="#ffc400" class="pay-btn" block>生成订单</van-button>
    </div>
  </div>
</template>

<script>
import Header from '../../components/Header.vue'
import {reactive,toRefs,onMounted} from 'vue'
import {useStore} from 'vuex'
import { Dialog } from 'vant'
import { useRouter,useRoute } from 'vue-router'
export default {
  components:{
    Header,
  },
  setup(){
    const router =new useRouter();
     const route =new useRoute();
    const store=new useStore();
    let data= reactive({
      name:'喜羊羊',
      tel:13680657816,
      allPrice:0,
    })
    // 点击可编辑地址详细信息
    const onEdit=()=>{
      router.push('./address')
    }
    // 点击生成订单按钮
    const handleCreateOrder=()=>{
      Dialog.alert({
      title: '提示',
      message: '恭喜！你的订单已完成！',
      }).then(() => {
        let newList=store.state.cartList.filter((item)=>{
          return !route.query.list.includes(item.id+"")
        })
        store.commit('DELETE',newList);
        store.commit('UPDATEORDER')
        router.push('./order')
      });
      
    }
    // 初始化计算总价格
    const initPrice=()=>{
      let price=0;
      if(store.state.orderList.length){
        store.state.orderList.forEach((item)=>{
          price+=item.num*item.price;
        })
        data.allPrice=price;
      }
    }
    // 用户信息初始化
    const initUser=()=>{
      store.state.userAddress.forEach((item)=>{
        if(item.isDefault){
          data.name=item.name;
          data.tel=item.tel;
        }
      })
    }

    onMounted(()=>{
      initPrice();
      initUser();
    })
    return {
      ...toRefs(data),onEdit,store,handleCreateOrder,initPrice,initUser
    }
  }
}
</script>

<style lang="less" scoped>
.create_order {
  display:flex;
  flex-flow: column;
  height: 100%;
  .content {
    flex: 1;
    overflow-y:auto;
  }
  .pay-wrap{
    padding: 0 5px;
    width: 100%;
    background-color: #fff;
    border-top: 1px solid #e9e9e9;
    >div{
      display:flex;
      justify-content:space-between;
      padding: 0 5%;
      margin:10px 0;
      font-size:16px;
      span:nth-child(2){
        color: red;
        font-size: 20px;
      }
    }
    .pay-btn {
      width: 90%;
      margin: 0 auto;
    }
  }
}
</style>